#!/bin/bash

set -e
set -o pipefail

handle_error() {
  local exit_code=$?
  echo "Error occurred in script at line: ${1} with exit code: ${exit_code}"
  exit $exit_code
}

trap 'handle_error ${LINENO}' ERR

AK=$1
SK=$2
OBS_ENDPOINT=$3
TAG=$4
OLD_TAG=$5

SOURCE_BUCKET="openubmc-dailybuild"
DST_BUCKET="openubmc-repo"
PREFIX_PATH="pre_release"
CVE_MANAGER_URL="https://cvemanager-ng.osinfra.cn/api/manage/bulletin/release"

cur_path=$(pwd)

chmod +x scripts/common_scripts/common.sh
source scripts/common_scripts/common.sh

function prepare_python_dependency() {
  cd ${cur_path}
  pip3 install -r scripts/publish_pipeline/publish_package/requirements.txt
}

function prepare_env() {
  prepare_software
  prepare_python_dependency
}

function build() {
  # transfer the obs
  cd ${cur_path}
  chmod +x scripts/publish_pipeline/publish_package/publish_community_transfer_obs.py
  ./scripts/publish_pipeline/publish_package/publish_community_transfer_obs.py --ak=${AK} --sk=${SK} --obs_endpoint=${OBS_ENDPOINT} --from_obs_bucket_name=${SOURCE_BUCKET} --destination_bucket_name=${DST_BUCKET} --prefix_path=${PREFIX_PATH}

  # send message to cve-manager
  cd ${cur_path}
  chmod +x scripts/publish_pipeline/publish_package/publish_community_cve.py
  ./scripts/publish_pipeline/publish_package/publish_community_cve.py --cve_manager_url=${CVE_MANAGER_URL} --affected_tag=${OLD_TAG} --fixed_tag=${TAG}

  # send message to kafka
  cd ${cur_path}
  chmod +x scripts/publish_pipeline/publish_package/publish_community_message.py
  ./scripts/publish_pipeline/publish_package/publish_community_message.py --tag=${TAG}

}

function main() {
  prepare_env
  build
}

echo "===start to publish Community==="
main
echo "===end to publish Community==="
exit 0
